package com.jddup.program.utils;

import com.jddup.common.enums.JdbcTypeEnums;
import org.apache.commons.lang3.StringUtils;

/**
 * Created by ZZB on 2017/12/4.
 */
public class DatabaseUtils {
    /**
     * 通过url获取jdbc类型
     */
    public static JdbcTypeEnums getJdbcTypeEnumsByUrl(String connectionUrl) {
        if (connectionUrl.contains("jtds")) {
            return JdbcTypeEnums.JTDS;
        }
        if (connectionUrl.contains("sqlserver")) {
            return JdbcTypeEnums.SQLSERVER;
        }
        if (connectionUrl.contains("mysql")) {
            return JdbcTypeEnums.MYSQL;
        }
        if (connectionUrl.contains("postgresql")) {
            return JdbcTypeEnums.POSTGRESQL;
        }
        return null;
    }

    //获取jdbcUrl链接
    public static String getJdbcUrl(String jdbcDriver, String serverHost, String serverPort, String dbName, String schema) {
        StringBuilder sb = null;
        if (jdbcDriver.equals("org.postgresql.Driver")) {
            sb = new StringBuilder("jdbc:postgresql://")
                    .append(serverHost)
                    .append(":")
                    .append(serverPort)
                    .append("/")
                    .append(dbName);
        } else if (jdbcDriver.equals("net.sourceforge.jtds.jdbc.Driver")) {
            sb = new StringBuilder("jdbc:jtds:sqlserver://")
                    .append(serverHost)
                    .append(StringUtils.isBlank(serverPort) ? "" : (":" + serverPort))
                    .append("/")
                    .append(dbName);
        } else if (jdbcDriver.equals("org.apache.hive.jdbc.HiveDriver")) {
            sb = new StringBuilder("jdbc:hive2://")
                    .append(serverHost)
                    .append(StringUtils.isBlank(serverPort) ? "" : (":" + serverPort))
                    .append("/")
                    .append(dbName);
        } else {
            sb = new StringBuilder("jdbc:mysql://")
                    .append(serverHost)
                    .append(":")
                    .append(serverPort)
                    .append("/")
                    .append(schema)
                    .append("?useUnicode=true&characterEncoding=utf-8&mysqlEncoding=utf8&autoReconnect=true&zeroDateTimeBehavior=convertToNull");
        }
        return sb.toString();
    }
}
